package com.taotao.sso.service.impl;

import com.baobao.common.service.RedisService;
import com.baobao.common.utils.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.User;
import com.taotao.sso.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RedisService redisService;



	//type为类型，可选参数1、2、3分别代表username、phone、email

	@Override
	public Boolean checkUser(String param, Integer type) {
		User user = new User();
		switch (type) {
		case 1:
			user.setUsername(param);
			break;
		case 2:
			user.setPhone(param);
			break;
		case 3:
			user.setEmail(param);
			break;
		}
		
		
		return this.userMapper.selectCount(user)==0;
	}

	//用户的注册
	@Override
	public Boolean addUser(User user) {
		user.setId(null);
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		
		return this.userMapper.insertSelective(user)==1;
	}

	@Override
	public String login(String username, String password) throws JsonProcessingException {
		User record = new User();
		record.setUsername(username);
		User user = this.userMapper.selectOne(record);
		if (user==null){
			return null;
		}
		if (!StringUtils.equals(user.getPassword(),DigestUtils.md5Hex(password))){
			return null;
		}
		String token = DigestUtils.md5Hex(username+System.currentTimeMillis());
		this.redisService.setex("TOKEN:"+token,JsonUtils.toString(user),1800);
		return token;
	}

	@Override
	public User getUserInfo(String token) throws IOException {
				String key = "TOKEN:"+token;
				String userJson = this.redisService.get(key);
		if (StringUtils.isEmpty(userJson)){
			return null;
		}
		User user = JsonUtils.toBean(userJson, User.class);
		return user;

	}
}
